﻿using Microsoft.AspNetCore.Builder;

namespace Framework.WebApi.Swagger
{
	public static class SwaggerWebApplicationExtension
	{
		/// <summary>
		/// 添加规范化文档中间件
		/// </summary>
		/// <param name="webApplication"></param>
		/// <param name="routePrefix"></param>
		public static void UseSwaggerWeb(this IApplicationBuilder webApplication, string routePrefix = default)
        {
			// 读swagger配置
			var swaggerSetting = App.GetConfig<SwaggerSetting>("SwaggerSetting");

			if (!swaggerSetting.EnableSwagger) return;	// 判断是否启用Swagger

			webApplication.UseSwagger(c =>
			{
				//c.PreSerializeFilters.Add((swaggerDoc, httpReq) => { ApiRusltFilter.ApiRuslt(swaggerDoc, httpReq); });
			});

			// 配置 Swagger UI 参数
			webApplication.UseSwaggerUI(c =>
			{
				var customIndex = $"{Assembly.GetExecutingAssembly().GetName().Name}.html.index.html";
				c.IndexStream = (Func<Stream>)(() => Assembly.GetExecutingAssembly().GetManifestResourceStream(customIndex));
				c.RoutePrefix = swaggerSetting.RoutePrefix ?? routePrefix ?? "api";
				c.SwaggerEndpoint("/swagger/v1/swagger.json", swaggerSetting.Title + " " + swaggerSetting.Version);
			});

			if (!App.GetConfig<Boolean>("EnableMiniProfiler")) return;  // 判断是否启用MiniProfiler

			// 激活MiniProfiler中间件，启用MiniProfiler服务，放在UseEndpoints方法之前。
			webApplication.UseMiniProfiler();
		}
	}
}
